import React, { Component } from 'react';
import { Button, Table, Card, Checkbox, Icon, message, Spin } from 'antd';
import { postGenSysQuestion, getGenSysQuestionStatus, postGenSysQuestionList, postGenSysQuestionAdd } from '@/services/similarExt';
import { getKnowledgeDetail } from '@/services/knowledgemanagement';
import UserSession from "@/UserSession";
import { fetchNodeDetailByNodeId, knowledgeAtlasNodeDetail } from '@/services/knowledgegraph';
import NONE from '@/assets/u2713.png';

import styles from './index.less';
class SystemQuestion extends Component {
  state = {
    originalQueryData: {
      current: 1,
      size: 0,
    },
    originalSimilarToAsk: {
      list: [],
      total: 0,
    },
    originalIds: [],
    originalRows: [],
    systemQueryData: {
      current: 1,
      size: 999999,
    },
    systemSimilarToAsk: {
      list: [],
      total: 0,
    },
    systemIds: [],
    systemRows: [],
    logins: false,
    systemData: null,
    indeterminate: false,
    systemChecked: false,
    dataList: [],
    generateInfo: 'NONE',
  };

  componentDidMount() {
    const { qaType } = this.props;
    switch (qaType) {
      case 'knowledgeBase':
        this.getOriginalList();
        break;
      case 'knowledgeMap':
        this.getNodeOriginalList();
        break;
    }

    this.getSystemstatus();
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  // 知识点相似问
  getOriginalList = async () => {
    const { questionId } = this.props;
    const res = await getKnowledgeDetail({ id: questionId });
    console.log(res);
    let questions = res.questions && res.questions.length > 0 ? res.questions : [];
    let knowledgeQuestionList = res.basicQuestion ? [res.basicQuestion, ...questions] : questions;
    let list = knowledgeQuestionList.map((item, index) => { return { question: item, id: index + 1 } });
    let originalSimilarToAsk = { list, total: knowledgeQuestionList.length };
    this.setState({ originalSimilarToAsk, dataList: questions });
  }

  // 导图节点相似问
  getNodeOriginalList = async () => {
    const { questionId } = this.props;
    let res = null;
    if (UserSession.isSystemKnowledge()) {
      res = await knowledgeAtlasNodeDetail({ nodeId: questionId });
    } else {
      res = await fetchNodeDetailByNodeId({ id: questionId });
    };
    console.log(res);
    let alikeQuestion = res?.alikeQuestion && res?.alikeQuestion.length > 0 ? res?.alikeQuestion : [];
    let knowledgeQuestionList = res?.basicQuestion ? [res.basicQuestion, ...alikeQuestion] : alikeQuestion;;
    let list = knowledgeQuestionList.map((item, index) => { return { question: item, id: index + 1 } });
    let originalSimilarToAsk = { list, total: knowledgeQuestionList.length };
    this.setState({ originalSimilarToAsk, dataList: alikeQuestion });
  }

  // 生成系统相似问
  generateQuestion = async () => {
    const { originalRows } = this.state;
    const { questionId } = this.props;
    let questions = originalRows.map(item => item.question);
    let obj = { questions, qaId: questionId };
    let res = await postGenSysQuestion(obj);
    console.log(res);
    if (res.code == 0) {
      // message.success('操作成功');
      this.getSystemstatus();
    }
  }

  // 生成相似问状态
  getSystemstatus = async () => {
    const { questionId } = this.props;
    let res = await getGenSysQuestionStatus({ qaId: questionId });
    console.log(res);
    switch (res.status) {
      case 'wait':
        this.setState({ logins: true }, () => {
          setTimeout(() => this.getSystemstatus(), 5000)
        });
        break;
      case 'success':
        this.setState({ logins: false, systemData: res, originalIds: [], originalRows: [] }, () => {
          this.getSystemList()
        });
        break;
      case 'none':
        this.setState({ logins: false, generateInfo: 'NONE' });
        break;
    }
  }

  setSelectedRows = (selectedRowKeys, selectedRows) => {
    if (selectedRows.length > 10) {
      return message.error('每次最多选择10个句子生成相似问，请分批生成相似问');
    }
    this.setState({ originalIds: selectedRowKeys, originalRows: selectedRows });
  }

  getSystemList = async () => {
    const { questionId } = this.props;
    const { systemQueryData, systemData } = this.state;
    let obj = { ...systemQueryData, qaId: questionId, taskId: systemData.taskId };
    let res = await postGenSysQuestionList(obj);
    console.log(res);
    let systemSimilarToAsk = { list: res.records, total: res.total };
    this.setState({ systemSimilarToAsk, generateInfo: res.total > 0 ? '' : 'EMPTY' });
  }

  onCheckAllChange = () => {
    const { systemRows, systemSimilarToAsk } = this.state;
    let systemIds = null, systemList = null;
    if (systemRows.length >= 0 && systemRows.length < systemSimilarToAsk.total) {
      systemIds = systemSimilarToAsk.list.map(item => item.id);
      systemList = systemSimilarToAsk.list;
      this.setState({ systemChecked: true, indeterminate: false })
    } else {
      systemIds = [], systemList = [];
      this.setState({ systemChecked: false, indeterminate: false })
    }
    this.setState({ systemIds, systemRows: systemList })
  }

  remove = row => {
    const { systemSimilarToAsk, systemRows } = this.state;
    let list = [];
    systemSimilarToAsk.list.map((item, index) => {
      if (item.question != row.question) {
        list.push(item);
      }
    });
    let lists = [], listIds = [];
    systemRows.map((item, index) => {
      if (item.question != row.question) {
        lists.push(item);
        listIds.push(item.id);
      }
    });
    this.setState({
      systemSimilarToAsk: {
        list,
        total: list.length
      },
      systemIds: listIds,
      systemRows: lists
    });
  }

  addSimilarToAsk = async () => {
    const { systemRows, dataList } = this.state;
    const { similarExtensionAsk, questionId, qaType } = this.props;
    let data = systemRows.map(item => item.question);
    let dataType;
    switch (qaType) {
      case 'knowledgeBase':
        dataType = 1;
        break;
      case 'knowledgeMap':
        dataType = 2;
        break;
    }
    let obj = { questions: data, qaId: questionId, qaType: dataType };
    let res = await postGenSysQuestionAdd(obj);
    if (res.code == 0) {
      message.success('操作成功');
      switch (qaType) {
        case 'knowledgeBase':
          this.getOriginalList();
          break;
        case 'knowledgeMap':
          this.getNodeOriginalList();
          break;
      }
      this.setState({
        systemSimilarToAsk: {
          list: [],
          total: 0,
        },
        logins: false,
        generateInfo: 'NONE',
        systemIds: [],
        systemRows: [],
      }, () => {
        let questionList = [...data, ...dataList];
        similarExtensionAsk(questionList);
      })
    }
  }

  render() {
    const {
      originalQueryData, originalSimilarToAsk, originalIds, originalRows, systemQueryData,
      systemSimilarToAsk, systemIds, systemRows, logins, indeterminate, systemChecked, generateInfo,
    } = this.state;
    const originalHead = () => {
      return <div className={styles.originalHeader}>
        <p style={{ margin: 0 }}>
          <span style={{ fontWeight: 600 }}>{`已选：${originalRows.length}/10`}</span>
          <span style={{ marginLeft: 16 }}>一次性最多选择10个</span>
        </p>
        <p style={{ margin: 0 }}>
          <Button
            type="primary"
            size="small"
            onClick={this.generateQuestion}
            disabled={originalRows.length > 0 ? false : true}
          >生成相似问</Button>
        </p>
      </div>
    };
    const systemHead = () => {
      return <div className={styles.systemHeader}>
        <p style={{ margin: 0 }}>
          <Checkbox
            indeterminate={indeterminate}
            onChange={this.onCheckAllChange}
            checked={systemChecked}
          > 全选 </Checkbox>
          <span style={{ fontWeight: 600 }}>{`${systemRows.length}/${systemSimilarToAsk.total}`}</span>
        </p>
        <p style={{ margin: 0 }}>
          <Button
            type="primary"
            size="small"
            disabled={systemRows.length > 0 ? false : true}
            onClick={this.addSimilarToAsk}
          >添加到知识点</Button>
        </p>
      </div>
    };
    const rowSelectionOriginal = {
      selectedRowKeys: originalIds,
      onChange: this.setSelectedRows,
    };
    const rowSelectionSystem = {
      selectedRowKeys: systemIds,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(selectedRowKeys, selectedRows);
        let indeterminate = selectedRows.length > 0 && selectedRows.length < systemSimilarToAsk.total ? true : false;
        let systemChecked = selectedRows.length == systemSimilarToAsk.total ? true : false;
        this.setState({ systemIds: selectedRowKeys, systemRows: selectedRows, indeterminate, systemChecked });
      },
    };
    const originalColumns = [{
      title: '问题',
      dataIndex: 'question',
      render: text => {
        if (text.length > 16) {
          return <span title={text} style={{ whiteSpace: 'nowrap' }}>{text.slice(0, 16)}...</span>
        } else {
          return <span style={{ whiteSpace: 'nowrap' }}>{text}</span>
        }
      }
    }];
    const systemColumns = [{
      title: '',
      dataIndex: 'question',
      render: text => {
        if (text.length > 15) {
          return <span title={text} style={{ whiteSpace: 'nowrap' }}>{text.slice(0, 15)}...</span>
        } else {
          return <span style={{ whiteSpace: 'nowrap' }}>{text}</span>
        }
      }
    }, {
      title: '',
      render: (_, row) => {
        return (
          <Icon
            type="close-circle"
            style={{ fontSize: '18px', color: '#a3a3a3' }}
            onClick={() => this.remove(row)}
          />
        )
      }
    }];

    return (
      <div className={styles.systemQuestion}>
        <div style={{ width: 'calc(50% - 10px)' }}>
          <div>请选择需要生成相似问的句子</div>
          <Card title={originalHead()}>
            <Table
              dataSource={originalSimilarToAsk.list}
              rowSelection={rowSelectionOriginal}
              columns={originalColumns}
              rowKey={"id"}
              showHeader={false}
            />
          </Card>
        </div>
        <div style={{ width: 'calc(50% - 10px)' }}>
          <div>系统生成相似问</div>
          <Card title={systemHead()}>
            <Spin tip="正在生成相似问中..." spinning={logins}>
              {generateInfo == 'NONE' ? (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <p> <img src={NONE} width="100" /> </p>
                  <p style={{ textAlign: 'justify' }}>请选择左侧部分的句子，系统通过同义词替换、扩展增加、主干提取和句子改写等方式批量生成和目标句子意思相近的同义句。该能力适用于知识维护初期的知识点创建，提供相似问维护效率。</p>
                </div>
              ) : generateInfo == 'EMPTY' ? (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <p> <Icon type="stop" style={{ fontSize: '50px', color: '#bfbfbf' }} /> </p>
                  <p style={{ textAlign: 'justify' }}>抱歉，系统无法生成你选择的句子。您可以通过自动推荐和从问题库中添加的方式生成相似问。</p>
                </div>
              ) : (
                <Table
                  dataSource={systemSimilarToAsk.list}
                  rowSelection={rowSelectionSystem}
                  rowKey={"id"}
                  columns={systemColumns}
                  showHeader={false}
                />
              )}
            </Spin>
          </Card>
        </div>
      </div>
    );
  }
}

export default SystemQuestion;
